<template>
<!-- 文章列表组件 -->
<!-- 1.下拉刷新 -->
<!-- 2.滚动加载 -->
  <div class="article-list">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh"  success-text="刷新成功">

        <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
        >
         <!-- 文章列表项 -->
            <ActicleItem :article='item' v-for="(item,index) in list" :key="index"></ActicleItem>
            <!-- <van-cell v-for="(item,index) in list" :key="index" :title="item.title" /> -->
        </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/acticle'
import ActicleItem from '@/components/article-item'
export default {
  name: 'article-list',
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false, // 加载状态
      finished: false, // 是否去部加载完成
      refreshing: false,
      timestamp: +new Date()
    }
  },
  methods: {
    // 滚动加载
    async onLoad () {
      // 异步更新数据
      // 思路
      // 1. 请求数据
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp,
          with_top: 1
        })
        // console.log(data.data.results)
        this.list.push(...data.data.results)
        // 2. 将请求的数据添加到list中,记录本此请求的时间戳
        this.timestamp = data.data.pre_timestamp
        // (list组件会自动打开loading状态，我们只需要关闭)
        // 3.关闭loading状态
        this.loading = false
        // 4.判断是否列表加载结束
        // 判断加载条数是否等于十
        if (data.data.results.length < 10) {
        //      如果结束，将finish变为true
          this.finished = true
        }
        //      不动
      } catch (err) {
        // 请求错误停止加载
        this.loading = false
        this.finished = true
        this.$toast('获取失败')
      }
    },
    // 下拉刷新
    async onRefresh () {
    // 1.默认会打开refershi标识，
      try {
        // 2.发送请求，拿到数据
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: +new Date(),
          with_top: 1
        })
        console.log(data.dataresults)
        // 3.将拿到的数据放到数组前面
        this.list.unshift(...data.data.results)

        // 4. 关闭下拉标识
        this.refreshing = false
      } catch (error) {
        this.$toast('刷新失败')
        this.refreshing = false
      }
    }

  },
  components: {
    ActicleItem
  }

}
</script>

<style scoped>
    .article-list{
      height: calc(100vh - 274px);
      overflow-y: auto;
    }
     .doge {
    width: 200px;
    height: 72px;
    margin-top: 8px;
    border-radius: 4px;
  }
</style>
